// pages/travel/edit/index.ts
import { travelApi } from '../../../utils/api';
import { requireAuth } from '../../../utils/auth';

Page({
  data: {
    recordId: 0,
    formData: {
      title: '',
      description: '',
      location: '',
      latitude: null as number | null,
      longitude: null as number | null,
      start_date: '',
      end_date: '',
      images: [] as string[],
    },
    deletedImages: [] as string[],
    loading: false,
    isEditing: false,
  },

  onLoad(options: any) {
    const { id } = options;
    if (id) {
      this.setData({ recordId: parseInt(id), isEditing: true });
      this.loadRecordData(parseInt(id));
    }
  },

  async loadRecordData(id: number) {
    this.setData({ loading: true });

    try {
      const record: any = await travelApi.getDetail(id);
      this.setData({
        formData: {
          title: record.title || '',
          description: record.description || '',
          location: record.location || '',
          latitude: record.latitude || null,
          longitude: record.longitude || null,
          start_date: record.start_date || this.formatDate(new Date()),
          end_date: record.end_date || this.formatDate(new Date()),
          images: record.images || [],
        },
      });
    } catch (error) {
      console.error('加载旅游记录失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none',
      });
      wx.navigateBack();
    } finally {
      this.setData({ loading: false });
    }
  },

  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 输入框变化处理
  onInputChange(e: any) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: value,
    });
  },

  // 选择开始日期
  onStartDateChange(e: any) {
    this.setData({
      'formData.start_date': e.detail.value,
    });
  },

  // 选择结束日期
  onEndDateChange(e: any) {
    this.setData({
      'formData.end_date': e.detail.value,
    });
  },

  // 选择位置
  async onChooseLocation() {
    try {
      const res = await wx.chooseLocation({});
      if (res && res.name && res.latitude && res.longitude) {
        this.setData({
          'formData.location': res.name,
          'formData.latitude': res.latitude,
          'formData.longitude': res.longitude,
        });
      } else {
        // 用户可能取消了选择或者选择无效
        console.log('位置选择取消或无效');
      }
    } catch (error) {
      console.error('选择位置失败:', error);
      wx.showToast({
        title: '选择位置失败',
        icon: 'none',
      });
    }
  },

  // 选择图片（本地预览）
  async onUploadImage() {
    try {
      const res = await wx.chooseImage({
        count: 9,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
      });

      // 读取图片文件并转换为base64用于预览和后续提交
      const imagePromises = res.tempFilePaths.map(async (tempFilePath) => {
        try {
          const fileData = await new Promise<string>((resolve, reject) => {
            wx.getFileSystemManager().readFile({
              filePath: tempFilePath,
              encoding: 'base64',
              success: (res) => resolve(res.data as string),
              fail: reject,
            });
          });
          return `data:image/jpeg;base64,${fileData}`;
        } catch (error) {
          console.error('读取图片失败:', error);
          return null;
        }
      });

      const base64Images = (await Promise.all(imagePromises)).filter(Boolean) as string[];
      
      // 更新图片列表（显示预览）
      const images = this.data.formData.images.concat(base64Images);
      this.setData({
        'formData.images': images.slice(0, 9), // 最多9张图片
      });

      wx.showToast({
        title: `添加了 ${base64Images.length} 张图片`,
        icon: 'success',
      });

    } catch (error) {
      console.error('选择图片失败:', error);
      wx.showToast({
        title: '选择图片失败',
        icon: 'none',
      });
    }
  },

  // 删除图片
  onRemoveImage(e: any) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.formData.images];
    const deletedImage = images[index];
    images.splice(index, 1);
    
    this.setData({
      'formData.images': images,
    });

    // 如果是已存在的图片（URL格式），记录到待删除列表
    if (deletedImage.startsWith('https://')) {
      const deletedImages = this.data.deletedImages || [];
      deletedImages.push(deletedImage);
      this.setData({
        deletedImages: deletedImages,
      });
    }
  },

  // 预览图片
  onPreviewImage(e: any) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.formData.images[index],
      urls: this.data.formData.images,
    });
  },

  // 提交表单
  async onSubmit() {
    // 检查登录状态
    if (!requireAuth()) {
      return;
    }

    if (!this.validateForm()) {
      return;
    }

    this.setData({ loading: true });

    try {
      // 分离base64图片和已存在的URL图片
      const base64Images = this.data.formData.images.filter(img => img.startsWith('data:image/'));
      const existingImages = this.data.formData.images.filter(img => img.startsWith('https://'));

      const travelData = {
        ...this.data.formData,
        images: [...base64Images, ...existingImages], // 保持原有顺序
        deleted_images: this.data.deletedImages || [],
      };

      if (this.data.isEditing) {
        await travelApi.update(this.data.recordId, travelData);
        wx.showToast({
          title: '更新成功',
          icon: 'success',
          duration: 2000,
        });
      } else {
        await travelApi.create(travelData);
        wx.showToast({
          title: '创建成功',
          icon: 'success',
          duration: 2000,
        });
      }

      setTimeout(() => {
        wx.navigateBack();
      }, 2000);

    } catch (error: any) {
      console.error('操作失败:', error);
      
      // 检查是否是认证错误
      if (error.detail === '身份认证信息未提供。' || error.message === '登录已过期') {
        wx.navigateTo({
          url: '/pages/login/index',
        });
      } else {
        wx.showToast({
          title: error.message || (this.data.isEditing ? '更新失败' : '创建失败'),
          icon: 'none',
        });
      }
    } finally {
      this.setData({ loading: false });
    }
  },

  // 删除记录
  async onDelete() {
    // 检查登录状态
    if (!requireAuth()) {
      return;
    }

    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条旅游记录吗？',
      success: async (res) => {
        if (res.confirm) {
          this.setData({ loading: true });

          try {
            await travelApi.delete(this.data.recordId);
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000,
            });

            setTimeout(() => {
              wx.navigateBack();
            }, 2000);

          } catch (error) {
            console.error('删除失败:', error);
            wx.showToast({
              title: '删除失败',
              icon: 'none',
            });
          } finally {
            this.setData({ loading: false });
          }
        }
      },
    });
  },

  // 表单验证
  validateForm(): boolean {
    const { title, location, start_date, end_date } = this.data.formData;

    if (!title.trim()) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none',
      });
      return false;
    }

    if (!location.trim()) {
      wx.showToast({
        title: '请选择位置',
        icon: 'none',
      });
      return false;
    }

    if (!start_date) {
      wx.showToast({
        title: '请选择开始日期',
        icon: 'none',
      });
      return false;
    }

    if (!end_date) {
      wx.showToast({
        title: '请选择结束日期',
        icon: 'none',
      });
      return false;
    }

    // 验证结束日期不早于开始日期
    if (new Date(end_date) < new Date(start_date)) {
      wx.showToast({
        title: '结束日期不能早于开始日期',
        icon: 'none',
      });
      return false;
    }

    return true;
  },
});
